<template>
  <div class="page">
    <div class="player-wrap">
      <div class="top-container">
        <div class="operation">
          <div class="icon"><LeftOutlined :style="{ fontSize: '20px' }" /></div>
          <div class="text">{{ liveDetail.liveTitle }}</div>
        </div>
        <div class="space"></div>
      </div>
      <div id="container" class="player-container"></div>
      <div class="info-wrap">
        <div class="video-info">
          <div class="video-title">{{ liveDetail.liveTitle }}</div>
          <div class="course-info">
            <div class="speaker-info">讲师：{{ liveDetail.expertName }}老师</div>
            <div class="view-num">观看人数：{{ liveDetail.viewNum || 0 }} 人</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onBeforeMount, onMounted, onBeforeUnmount } from "vue";
import { message } from 'ant-design-vue';
import { useRoute } from 'vue-router';
import { LeftOutlined } from '@ant-design/icons-vue';
import Aliplayer from "aliyun-aliplayer";
import "aliyun-aliplayer/build/skins/default/aliplayer-min.css";
import useAppStore from "@/stores/app";
import appConfig from '@/config';
import { base58Decode, unit8ArrayToString } from '@/utils/base58';
import { miscApi } from "@/services";

const route = useRoute();
const storeApp = useAppStore();
const liveDetail = ref({});

onBeforeMount(async () => {
  storeApp.startLoading();
});

onMounted(async () => {
  const roomInfo = route.query.id;
  console.log("live room id: ", roomInfo);
  if (!roomInfo) {
    message.error('播放异常，获取不到课程id信息');
    return false;
  }

  liveDetail.value = JSON.parse(unit8ArrayToString(base58Decode(roomInfo)));
  console.log("live detail: ", liveDetail.value);
  
  if (!liveDetail.value.status) {
    message.error('直播尚未开始，请稍后重试');
    return false;
  }

  // 创建新的播放器
  await createPlayer();

  miscApi.traceViewPage('/live/index', roomInfo);

  storeApp.endLoading();
});

onBeforeUnmount(() => {
  // 销毁当前播放器
  if (player.value) {
    player.value.dispose();
  }
});

const isLiving = () => {
  return liveDetail.value.status && liveDetail.value.status==1;
}

const getLiveUrl = () => {
  return liveDetail.value.liveUrl;
}

const player = ref<typeof Aliplayer>(null); // 播放器
const createPlayer = async () => {
  let options = {
    id: "container",
    width: "100%",
    height: "100%",
    cover: liveDetail.value.liveImg, // 视频封面
    autoplay: true, // 自动播放
    isLive: isLiving(),
    rePlay: false,
    playsinline: true,
    preload: true,
    language: "zh-cn",
    controlBarVisibility: "hover",
    useH5Prism: true,
    source: getLiveUrl(),
    license: {
      domain: appConfig.aliPlayerLicenseDomain, // 申请 License 时填写的域名
      key: appConfig.aliPlayerLicenseKey // 申请成功后，在控制台可以看到 License Key
    },
    skinLayout: [
      { name: "bigPlayButton", align: "cc" },
      { name: "controlBar", align: "blabs", x: 0, y: 0, children: [
          { name: "progress", align: "blabs", x: 0, y: 44 },
          { name: "playButton", align: "tl", x: 15, y: 12 },
          { name: "timeDisplay", align: "tl", x: 10, y: 7 },
          { name: "fullScreenButton", align: "tr", x: 10, y: 12 }
        ]
      }
    ],
    // components: [{
    //   name: 'QualityComponent',
    //   type: (window as any).AliPlayerComponent.QualityComponent,
    //   args: [function(definition,desc) {
    //     console.log(definition + '-----' + desc)
    //   }]
    // }]
  };

  // 更多使用方法请参考接入文档：https://help.aliyun.com/zh/vod/developer-reference/integration
  player.value = new Aliplayer(
    options,
    (player: typeof Aliplayer) => {
      // 播放下一个视频
      player.on("ended", async () => {
        
      });

      // 监听sourceloaded事件，查询视频的分辨率，调用分辨率组件并调用setCurrentQuality方法来设置分辨率
      player.on('sourceloaded', function(params) {
        var paramData = params.paramData
        var desc = paramData.desc
        var definition = paramData.definition
        player.getComponent('QualityComponent').setCurrentQuality(desc, definition)
      })
    },
  );
};
</script>

<style lang="less" scoped>
.page {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background: @white-bg;
  display: flex;
  flex-direction: row;

  .player-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;

    .top-container {
      width: 100%;
      height: 150px;
      display: flex;
      flex-direction: row;
      padding: 30px;
      color: @white;
      background: linear-gradient( 180deg, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0) 100%);
      position: absolute;
      top: 0px;
      left: 0px;
      z-index: 9999;

      .operation {
        width: 50%;
        height: 30px;
        line-height: 30px;
        display: flex;
        flex-direction: row;
        align-items: center;
        cursor: pointer;

        .icon {
          width: 30px;
          height: 30px;
          padding: 5px;
        }

        .text {
          height: 20px;
          line-height: 20px;
          font-size: 20px;
          font-weight: 500;
          color: @white;
          margin-left: 10px;
        }
      }
      
      .space {
        flex: 1;
      }
    }

    .player-container {
      width: 100%;
      flex: 1;
      /*aspect-ratio: 134 / 75;*/
      background-color: #000;
      /*margin-top: 20px;*/
      position: relative;
    }

    .info-wrap {
      display: flex;
      flex-direction: column;
      align-items: center;

      .video-info {
        width: 100%;
        height: 163px;
        background: @white-bg;
        padding: 30px;

        .video-title {
          height: 24px;
          line-height: 24px;
          font-size: 24px;
          font-weight: 500;
          color: @font-black;
        }

        .course-info {
          margin-top: 20px;
          display: flex;
          flex-direction: row;
          align-items: center;

          .speaker-info {
            height: 16px;
            line-height: 16px;
            font-size: 16px;
            font-weight: 400;
            color: @font-black;
          }

          .view-num {
            margin-left: 40px;
            color: @font-grey-light;
          }
        }
      }
    }
  }

  :deep(.prism-player .prism-controlbar) {
    .prism-controlbar-bg {
      height: 44px;
      background: rgba(0, 0, 0, .8);
    }
    .prism-progress .prism-progress-played {
      background-color: @text-link-color;
    }
  }
}
</style>